package br.com.ac.fatureweb.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.ac.fatureweb.exception.NgcException;
import br.com.ac.fatureweb.integration.enums.EnumStatus;
import br.com.ac.fatureweb.integration.model.EquipamentoVO;
import br.com.ac.fatureweb.model.Equipamento;
import br.com.ac.fatureweb.utilitary.NgcDefaultBean;
import br.com.ac.fatureweb.utilitary.Order;

@Local
@Named
@Stateless
public class NgcEquipamentoBean extends NgcDefaultBean<Equipamento> {

	@PersistenceContext
	private EntityManager entityManager;

	@PostConstruct
	void inicialize() {
		setEm(entityManager);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.ac.fatureweb.utilitary.NgcDefaultBean#persist(java.lang.Object)
	 */
	@Override
	public Equipamento persist(Equipamento entity) {
		entity.setDataCadastro(new Date());
		entity.setStatus(EnumStatus.ATIVO);
		return super.persist(entity);
	}

	/**
	 * Buscar os dados do equipamento solicitado.
	 * 
	 * @param imei
	 * @return
	 */
	public EquipamentoVO buscarEquipamento(String imei) {
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.ac.fatureweb.utilitary.NgcDefaultBean#remove(java.lang.Object)
	 */
	@Override
	public void remove(Equipamento entity) throws NgcException {
		validarAssociacaoComRoteiro(entity.getId());
		super.remove(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.com.ac.fatureweb.utilitary.NgcDefaultBean#remove(java.lang.Long)
	 */
	@Override
	public void remove(Long id) throws NgcException {
		validarAssociacaoComRoteiro(id);
		super.remove(id);
	}

	private void validarAssociacaoComRoteiro(Long id) throws NgcException {
		if (isRoteiroAssociado(id)) {
			throw new NgcException("Não é possível excluir equipamento, "
					+ "já existem roteiro associado ao mesmo.");
		}
	}

	@SuppressWarnings("unchecked")
	public boolean isRoteiroAssociado(Long idEquipamento) {
		Query query = entityManager
				.createQuery("SELECT rot.id FROM Roteiro rot "
						+ "INNER JOIN rot.equipamento eqe WHERE eqe.id =:id");

		query.setParameter("id", idEquipamento);

		List<Long> resultList = query.getResultList();

		if (resultList != null && !resultList.isEmpty()) {
			return true;
		}

		return false;
	}

}
